import {DataBase} from "../.."
export interface MiddlewareAPI {
    dispatch: (...args:any[])=>never;
    getState(): stateType;
}
export  interface Dispatch{
    (...argv:any[]):stateType;
    (actionTypes:actionTypes):stateType
}
export interface Middleware{
    (api: MiddlewareAPI): (next: Dispatch) => (action: actionTypes) => any;
}
// export function applyMiddleware<Ext, S = any>(...middlewares: Middleware<any, S, any>[]): StoreEnhancer<{dispatch: Ext}>;
import compose from "./compose"
import {
    StoreCreate, Reducer, stateType, StoreEnhancer,actionTypes
} from "./createStore";

export default function applyMiddleware(...middlewares: Middleware[]) {
    return (createStore: StoreCreate) => 
        // 重载 了整个 createStore
        (reducer: Reducer, preloadedState?: stateType | StoreEnhancer, enhancer?: StoreEnhancer) => {
            let store = createStore(reducer, preloadedState, enhancer);
            let dispatch = (...args:any[]) => {
                throw new Error(
                    `Dispatching while constructing your middleware is not allowed. ` +
                    `Other middleware would not be applied to this dispatch.`
                )
            }
            const middlewareAPI:MiddlewareAPI = {
                getState: store.getState,
                dispatch: dispatch
            }
            const chain = middlewares.map(middleware => middleware(middlewareAPI))

            store.dispatch = compose(...chain)(store.dispatch);
            return store
        };
}

